package action;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import model.Myboard;
import model.Mymember;

import com.oreilly.servlet.MultipartRequest;
import com.oreilly.servlet.multipart.DefaultFileRenamePolicy;

import daoServiceImpl.MyboardDAOImpl;
import daoServiceImpl.TempLoginInfo;

public class DoFrontController extends HttpServlet {

	private void execute(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		String uri = req.getRequestURI();
		String contextPath = req.getContextPath();
		String command = uri.substring(contextPath.length());
		System.out.println("command:" + command);

		req.setAttribute("header", "template/header.jsp");
		req.setAttribute("mainMenu", "template/mainMenu.jsp");
		req.setAttribute("footer", "template/footer.jsp");
		if (command.equals("/home.do")) {
			System.out.println("홈.do");
			req.setAttribute("sideMenu", "template/sideMenuHome.jsp");
			req.setAttribute("body", "template/bodyHome.jsp");
			req.getRequestDispatcher("home.jsp").forward(req, resp);
		} else if (command.equals("/company.do")) {
			System.out.println("컴패니.do");
			req.setAttribute("sideMenu", "company/sideMenu.jsp");
			req.setAttribute("body", "company/introduce.jsp");
			req.getRequestDispatcher("home.jsp").forward(req, resp);
		} else if (command.equals("/companyGallery.do")) {
			System.out.println("company갤러리.do");
			req.setAttribute("sideMenu", "company/sideMenu.jsp");
			req.setAttribute("body", "company/gallery.jsp");
			// 실제 경로
			String companyPath = req.getRealPath("image/company");
			File companyFile = new File(companyPath);
			// 해당 폴더안에 있는 모든 파일이름을 배열로 리턴
			String[] fileArray = companyFile.list();
			req.setAttribute("fileList", fileArray);
			req.getRequestDispatcher("home.jsp").forward(req, resp);

		} else if (command.equals("/board.do")) {
			System.out.println("보드.do");
			req.setAttribute("sideMenu", "board/sideMenu.jsp");
			req.setAttribute("body", "board/list.jsp");
			List<Myboard> list = new MyboardDAOImpl().selectAll();
			req.setAttribute("list", list);

			req.getRequestDispatcher("home.jsp").forward(req, resp);
		} else if (command.equals("/boardWriteForm.do")) {
			System.out.println("보드 글쓰기 폼.do");
			if(req.getSession().getAttribute("id")==null){
				System.out.println("로그인을 안했으니 글못써 "); 
				resp.sendRedirect("");  
			}else{
			 req.setAttribute("sideMenu", "board/sideMenu.jsp");
			 req.setAttribute("body", "board/writeForm.jsp");
			 req.getRequestDispatcher("home.jsp").forward(req, resp);
			} 
		}

		else if (command.equals("/boardWriteProc.do")) {
			String uploadPath = this.getServletContext().getRealPath("upload");
			int size = 10 * 1024 * 1024;// 10Mb 제한.
			String id = "", subject = "", content = "";
			ArrayList<String> fileNames = new ArrayList<String>();
			ArrayList<String> originalFileNames = new ArrayList<String>();
			try {// 생성하면 저장됩니다
				MultipartRequest multi = new MultipartRequest(req, uploadPath,
						size, "euc-kr", new DefaultFileRenamePolicy());
				id = multi.getParameter("id");
				subject = multi.getParameter("subject");
				content = multi.getParameter("content");
				// 업로드한 파일의 이름만 모두다 가져와라
				String[] fileNameArray = multi.getParameterValues("file");
				Enumeration<String> files = multi.getFileNames();
				while (files.hasMoreElements()) {
					String file = files.nextElement();
					System.out.println("file : " + file);
					// 수정된 파일명
					fileNames.add(multi.getFilesystemName(file));
					// 원래 파일명
					originalFileNames.add(multi.getOriginalFileName(file));
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
			System.out.println("보드 데이터 베이스 insert 요청.do");
			Myboard myboard = new Myboard(0, id, subject, content,
					fileNames.get(0), 0, null);
			// Ibatis의 명령을 호출하는 클래스의 insert메서드 호출
			new MyboardDAOImpl().insert(myboard);
			resp.sendRedirect("board.do");
		} else if (command.equals("/boardDetail.do")) {
			String num = req.getParameter("num");
			int n = Integer.parseInt(num);
			Myboard board = new MyboardDAOImpl().select(n);
			req.setAttribute("board", board);
			req.setAttribute("sideMenu", "board/sideMenu.jsp");
			req.setAttribute("body", "board/detail.jsp");
			req.getRequestDispatcher("home.jsp").forward(req, resp);
		} else if (command.equals("/boardDelete.do")) {
			String num = req.getParameter("num");
			int n = Integer.parseInt(num);
			System.out.println(new MyboardDAOImpl().delete(n));
			resp.sendRedirect("board.do");
		}

		else if (command.equals("/boardUpdateForm.do")) {
			String num = req.getParameter("num");
			int n = Integer.parseInt(num);
			Myboard board = new MyboardDAOImpl().select(n);
			req.setAttribute("board", board);
			req.setAttribute("body", "board/updateForm.jsp");
			req.setAttribute("sideMenu", "board/sideMenu.jsp");
			req.getRequestDispatcher("home.jsp").forward(req, resp);
		} else if (command.equals("/boardUpdateFormProc.do")) {
			int num = Integer.parseInt(req.getParameter("num"));
			String subject = req.getParameter("subject");
			String content = req.getParameter("content");
			Myboard board = new Myboard(num, "", subject, content, "file", 0,
					null);
			new MyboardDAOImpl().update(board);
			resp.sendRedirect("boardDetail.do?num=" + num);
		} else if (command.equals("/loginProc.do")) {
			String id = req.getParameter("id");
			String pw = req.getParameter("pw");
			// 임시로 여기서 id와 비번체크를 하겠습니다
			boolean loginCheck = false;
			for (int i = 0; i < TempLoginInfo.memberList.size(); i++) {
				Mymember member = TempLoginInfo.memberList.get(i);
				if (member.getId().equals(id) && member.getPw().equals(pw)) {
					System.out.println("로그인 성공");
					req.getSession().setAttribute("id", id);
					loginCheck = true;
					break;
				}
			}
			if (loginCheck) {
				resp.sendRedirect("home.do");
			} else {
				resp.sendRedirect("");
			}
		}else if (command.equals("/logout.do")) {
			req.getSession().removeAttribute("id");
			resp.sendRedirect("home.do"); 
		}
	}

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		execute(req, resp);
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		execute(req, resp);
	}

}
